package com.mars.common.web.support;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.dubbo.rpc.RpcException;
import com.alibaba.fastjson.JSON;
import com.mars.common.exception.BizException;
import com.mars.common.page.PageParam;
import com.mars.common.utils.CommonUtils;
import com.mars.common.utils.WebUtil;

/**
 * 基础控制类
 * 
 * @author 杨浩泉
 * @version 2016年10月14日
 */
public class BaseController extends SupperController implements HandlerInterceptor {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
	}
	
	/**
	 * 获取分页参数，包含当前页、每页记录数.
	 * @return
	 */
	public PageParam getPageParam() {
		return new PageParam(getPageNum(), getNumPerPage(), getOrderBy()) ;
	}
	public PageParam getPageParam(Integer page, Integer rows, String sort, String order) {
		return new PageParam(getPageNum(page), getNumPerPage(rows), getOrderBy(sort, order)) ;
	}
	public PageParam getPageParam(Integer page, Integer rows) {
		return new PageParam(getPageNum(page), getNumPerPage(rows), getOrderBy()) ;
	}

	/**
	 * 起始页
	 * @param page 通过URL传入起始页
	 * @return
	 */
	private int getPageNum(Integer page) {
		String pageNumStr = request.getParameter("page");
		int pageNum = 1;
		//通过URL指定起始页
		if(null != page) {
			pageNum = page ;
		}
		if (StringUtils.isNotBlank(pageNumStr)) {
			pageNum = Integer.valueOf(pageNumStr);
		}
		return pageNum;
	}
	private int getPageNum() {
		return getPageNum(null) ;
	}
	
	/**
	 * 获取每页记录数
	 * 如果没有值则默认返回20.
	 * @param rows 通过URL传入每页显示的记录数
	 * @return
	 */
	private int getNumPerPage(Integer rows) {
		String numPerPageStr = request.getParameter("rows");
		int numPerPage = 20;
		//通过URL指定每页显示多少条记录
		if(null != rows) {
			numPerPage = rows ;
		}
		if (StringUtils.isNotBlank(numPerPageStr)) {
			numPerPage = Integer.parseInt(numPerPageStr);
		}
		return numPerPage;
	}
	private int getNumPerPage() {
		return getNumPerPage(null) ;
	}

	/**
	 * 查询排序
	 * @param _sort 通过URL传入排序的类型
	 * @param _order 通过URL传入排序的字段
	 * @return
	 */
	private String getOrderBy(String _sort, String _order) {
		String sort = request.getParameter("sort");
		String order = request.getParameter("order");
		//通过URL排序类型
		if(null != _sort) {
			sort = _sort ;
		}
		//通过URL排序字段
		if(null != _order) {
			order = _order ;
		}
		if (CommonUtils.isNotEmpty(sort)) {
			return sort + " " + (CommonUtils.isNotEmpty(sort) ? order : "DESC") ;
		}
		return null ;
	}
	private String getOrderBy() {
		return getOrderBy(null, null) ; 
	}
	
	
	/**
	 * 统一异常处理
	 */
	@ExceptionHandler(Exception.class)
	public ModelAndView handleException(Exception e, HttpServletRequest request, HttpServletResponse response) {
		logger.error("Web统一异常处理", e);
		String requestType = request.getHeader("X-Requested-With");
		Map<String, Object> map = new HashMap<String, Object>();

		if (!"XMLHttpRequest".equals(requestType)) {// 非Ajax请求
			ModelAndView mv = new ModelAndView();
			map.put("request", WebUtil.getCurrentUrl(request, true));

			if (e instanceof BizException) {
				mv.setViewName("common/exception/500");
				mv.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
				map.put("status", mv.getStatus().value());
				map.put("message", e.getMessage());
				mv.addAllObjects(map);
			} else if (e instanceof RpcException) {
				mv.setViewName("common/exception/500");
				mv.setStatus(HttpStatus.SERVICE_UNAVAILABLE);
				map.put("status", mv.getStatus().value());
				map.put("message", "Dubbo分布式服务不可用<br>" + e.getMessage());

				mv.addAllObjects(map);
			} else {
				mv.setViewName("common/exception/500");
				mv.setStatus(HttpStatus.INTERNAL_SERVER_ERROR);
				map.put("status", mv.getStatus().value());
				map.put("message", e.getMessage());
				mv.addAllObjects(map);
			}
			return mv;

		} else {
			response.setContentType("application/json;charset=utf-8");
			PrintWriter out = null;
			try {
				out = response.getWriter();
				if (e instanceof BizException) {
					response.setStatus(500);
					map.put("status", response.getStatus());
					map.put("message", e.getMessage());
					map.put("request", WebUtil.getCurrentUrl(request, true));
					out.print(JSON.toJSONString(map));
				} else if (e instanceof RpcException) {
					response.setStatus(503);
					map.put("status", response.getStatus());
					map.put("message", "Dubbo分布式服务不可用<br>" + e.getMessage());
					map.put("request", WebUtil.getCurrentUrl(request, true));
					out.print(JSON.toJSONString(map));
				} else {
					response.setStatus(500);
					map.put("status", response.getStatus());
					map.put("message", e.getMessage());
					map.put("request", WebUtil.getCurrentUrl(request, true));
					out.print(JSON.toJSONString(map));
				}

			} catch (IOException ioEx) {
				ioEx.printStackTrace();
			} finally {
				out.flush();
				out.close();
			}
			return null;
		}
	}
}
